<template>
	<view class="review-box page-box">
		<view style="height: 148rpx;">
			<u-navbar bgColor="transparent" height="74">
				<view class="u-nav-slot flex-align-center" slot="left">
					<view class="back-box flex-center">
						<image class="image1" src="@/static/images/review/fanhui.png" @click="goBack" />
					</view>
					<span style="margin-left:33rpx">优题库</span>
				</view>
				<view slot="right" class="u-nav-slot-right flex-center">
					<view class="answer-sheet flex-align-center" @click="openQuestionCard">
						<image src="../../../../static/images/common/datika.png"></image>
						<span v-if="seeParse">答题卡 | {{ totalScore }} 分</span>
						<span v-else>答题卡 {{ current + 1 }}/{{ get_questionList.length }}</span>
					</view>
					<view v-if="seeParse != true" class="hand-in flex-center" @click="handIn">
						交卷{{ seeParse }}
					</view>
				</view>
			</u-navbar>
		</view>
		<view class="content">
			<view class="count-down-box">
				<u-count-down :time="countTime" ref="countDown" :autoStart="autoStart" format="mm:ss" @change="onChange"
					@finish="finishTime">
					<view class="time">
						<text>倒计时：</text>
						<text class="time__item">{{ timeData.minutes }}&nbsp;分</text>
						<text class="time__item">{{ timeData.seconds }}&nbsp;秒</text>
					</view>
				</u-count-down>
			</view>
			<view class="swiper-box">
				<swiper class="swiper" :current="current" :indicator-dots="indicatorDots" :autoplay="autoplay"
					:interval="interval" :duration="duration" @change="changeQuestionList">
					<swiper-item v-for="(item, index) in get_questionList" :key="item.id" class="swiper-item-box"
						style="position: relative;">
						<block v-if="item.detailInfo">
							<view class="flex-align-center">
								<view class="question-box">
									<view class="question-box-item" :class="setWidth(item)">
										<view class="title">
											{{ index + 1 }}.{{ item.detailInfo.question_type_name }}
										</view>
										<view class="name" v-html="item.detailInfo.question">
										</view>
									</view>
									<view class="question-box-item" :class="setWidth(item)"
										style="padding-left: 30rpx;">
										<view class="title"
											v-if="item.detailInfo.question_type_name === '完型填空题'||item.detailInfo.question_type_name === '选句填空题'">
											请选择以下选项</view>
										<view class="name" style="padding-left: 20rpx;"
											v-if="item.detailInfo.question_type_name === '完型填空题'">
											<view class="item-write flex-align-center"
												v-for="(i,idx) in item.detailInfo.get_item">
												<span class="question-number">{{idx+1}}.</span>
												<view class="flex-align-center" style="flex-wrap: wrap;">
													<block v-for="rightSon in i.optionAsList" :key="rightSon.key">
														<span class="item-write-sin flex-align-center"
															v-if="rightSon.value">
															{{rightSon.key}}.{{rightSon.value}}
														</span>
													</block>
												</view>
											</view>
										</view>
										<view class="" v-if="item.detailInfo.question_type_name === '任务型阅读'">
											<view class="item-write " v-for="(i,idx) in item.detailInfo.get_item">
												<view class="flex-align-center">
													<span class="question-number">{{idx+1}}.{{i.question}}</span>
												</view>
												<view class="task-read-input">
													<input type="text" />
												</view>
											</view>
										</view>
										<view class="" v-if="item.detailInfo.question_type_name === '选句填空题'">
											<view class="item-write flex-align-center"
												v-for="(i,idx) in item.detailInfo.get_item">
												<!-- <span class="question-number">{{idx+1}}.</span> -->
												<view class="flex-align-center" style="flex-wrap: wrap;">
													<block v-for="rightSon in i.optionAsList" :key="rightSon.key">
														<span class="item-write-sin flex-align-center"
															v-if="rightSon.value">
															{{rightSon.key}}:{{rightSon.value}}
														</span>
													</block>
												</view>
											</view>
										</view>
										<view class="" v-if="item.detailInfo.question_type_name === '阅读理解题'">
											<view class="tab-read-box flex-align-center">
												<view class="flex-align-center"
													v-for="(i,idx) in item.detailInfo.get_item">
													<span @click="changeReadTab(index,idx)" class="tab-read-box-item"
														:class="item.detailInfo.readCurrentTab === idx ?'current-read':'' ">第{{idx+1}}题</span>
													<view class="line" v-if="idx < item.detailInfo.get_item.length - 1">
													</view>
												</view>
											</view>
											<view class="read-select-box">
												<view class=""
													v-html="item.detailInfo.get_item[item.detailInfo.readCurrentTab].question">
												</view>
												<view class="topic-box" style="margin: 30rpx 0;">
													<block
														v-for="son in item.detailInfo.get_item[item.detailInfo.readCurrentTab].optionAsList"
														:key="son.key">
														<block v-if="son.value">
															<view class="topic-item flex-align-center"
																@click="chooseAsRead(son.key, index)"
																:class="getClass(item, son.key)">
																<view class="options-item">{{ son.key }}.{{ son.value }}
																</view>
															</view>
														</block>
													</block>
												</view>
											</view>
										</view>
									</view>
								</view>
								<block v-if="seeParse">
									<image v-if="item.asInfo.choose_as != item.detailInfo.correct_option"
										src="../../../../static/images/common/cuowu.png" class="error-icon" />
									<image v-else src="../../../../static/images/common/ok.png" class="error-icon" />
								</block>
							</view>
							<!-- 1文字2图片 -->
							<view class="topic-box" v-if="item.detailInfo.question_type_name === '单选题'">
								<block v-for="son in item.detailInfo.optionAsList" :key="son.key">
									<block v-if="son.value">
										<view class="topic-item flex-align-center" @click="chooseAs(son.key, index)"
											:class="getClass(item, son.key)">
											<view class="options-item">{{ son.key }}.{{ son.value }}</view>
										</view>
									</block>
								</block>
							</view>
							<view class="topic-box" v-if="item.detailInfo.question_type_name === '多选题'">
								<block v-for="son in item.detailInfo.optionAsList" :key="son.key">
									<block v-if="son.value">
										<view class="topic-item flex-align-center" @click="chooseAs(son.key, index)"
											:class="getClassMany(item, son.key)">
											<view class="options-item">{{ son.key }}.{{ son.value }}</view>
										</view>
									</block>
								</block>
							</view>
							<view class="topic-box" v-if="item.detailInfo.question_type_name === '判断题'">
								<block v-for="son in item.detailInfo.optionAsList" :key="son.key">
									<block v-if="son.value">
										<view class="topic-item flex-align-center" @click="chooseAs(son.key, index)"
											:class="getClass(item, son.key)">
											<view class="options-item">{{ son.key }}.{{ son.value === 'T' ? '正确' : '错误'
												}}
											</view>
										</view>
									</block>
								</block>
							</view>
						</block>
						<view class="parase-box" v-if="seeParse === true" @click="toParse(item)">
							解析
						</view>
					</swiper-item>
				</swiper>
				<view class="tips">
					左右滑动切换题目
				</view>
			</view>
		</view>
		<!-- 答题卡 -->
		<answerSheet ref="answerSheet" :seeParse="seeParse" :totalQuestion="totalQuestion" @chooseItem="chooseItem">
		</answerSheet>
		<!-- 解析答案 -->
		<parseAnswerVue ref="parseAnswerVue" :answerList="answerList"></parseAnswerVue>
	</view>
</template>

<script>
	import {
		paperExamApi,
		getPaperExamDetailApi,
		getPaperExamQuestionApi,
		addAnswerRecordApi
	} from '@/api/questionBank/index.js';
	import answerSheet from '../answerSheet/answerSheet.vue';
	import parseAnswerVue from '../parseAnswer/parseAnswer.vue';
	import store from '@/store/index.js'
	export default {
		components: {
			answerSheet,
			parseAnswerVue
		},
		data() {
			return {
				timeData: {},
				current: 6,
				indicatorDots: false,
				autoplay: false,
				interval: 2000,
				duration: 500,
				get_questionList: [], //试题列表
				totalQuestion: [],
				seeParse: false,
				answerList: [],
				totalScore: null,
				examRecordInfo: null, //考试记录信息
				countTime: 60 * 60 * 1000, //倒计时时长
				autoStart: false, //自动计时
			};
		},
		onLoad(options) {
			console.log();
			if (options.id) {
				// this.paperExam(options.id);
				this.paperExam(81)
			}
		},
		created() {

		},
		onShow() {

			const seeParse = uni.getStorageSync('seeParse');
			const totalScore = uni.getStorageSync('totalScore');
			const answerIndex = uni.getStorageSync('answerIndex');
			console.log(seeParse, 'seeParse');
			if (seeParse === true) {
				this.current = answerIndex;
				this.totalScore = totalScore;
				this.$refs.countDown.pause();
			}
			uni.setStorageSync('seeParse', null);
			uni.setStorageSync('totalScore', null);
			uni.setStorageSync('answerIndex', null);
			this.seeParse = seeParse;
		},
		beforeDestroy() {
			uni.$off('chooseAnswerParse')
		},
		mounted() {

		},
		methods: {
			// 设置宽度
			setWidth(item) {
				// console.log(item, 'item');
				const name = item.detailInfo.question_type_name
				if (name === '完型填空题' || name === '阅读理解题' || name === '选句填空题' || name === '任务型阅读') {
					return 'width50'
				} else {
					return 'width100'
				}
			},
			getClass(item, optionKey) {
				if (this.seeParse) {
					if (item.detailInfo.correct_option === optionKey) {
						return 'greenColor'
					} else if (item.asInfo.choose_as === optionKey) {
						return 'redColor'
					}
					// return item.asInfo.choose_as === optionKey
					// 	? ''
					// 	: 'redColor';
				} else {
					return item.asInfo.choose_as === optionKey ?
						'greenColor' :
						'';
				}
			},
			// 多选设置样式
			getClassMany(item, optionKey) {
				if (this.seeParse) {
					if (item.detailInfo.correct_option === optionKey) {
						return 'greenColor'
					} else if (item.asInfo.choose_as === optionKey) {
						return 'redColor'
					}
					// return item.asInfo.choose_as === optionKey
					// 	? ''
					// 	: 'redColor';
				} else {
					if (item.asInfo.choose_as_array.length > 0) {
						// console.log(item.detailInfo.correct_option);
						// console.log(optionKey);
						return item.asInfo.choose_as_array.includes(optionKey) ? 'choose_as' : ''
						// const correct_option = item.detailInfo.correct_option.split(',');
						// return item.asInfo.choose_as === optionKey ?
						// 	'choose_as' :
						// 	'';

					}

				}

			},
			// 开始考试
			async paperExam(paper_id) {
				const {
					data: res
				} = await paperExamApi({
					paper_id
				});
				// console.log(res, '考试记录');
				let examRecordInfo = {
					paper_id,
					...res.data
				}
				this.examRecordInfo = examRecordInfo;
				// this.autoStart = true;
				this.$refs.countDown.start();
				// console.log(paper_id, '试卷详情');
				this.getPaperExamDetail(paper_id)

			},
			// 获取试卷详情
			async getPaperExamDetail(id) {
				const {
					data: res
				} = await getPaperExamDetailApi({
					id
				});
				// console.log(res.data.get_question, 'res获取试卷详情');
				if (res.data.get_question.length > 0) {
					// 提取并合并所有 item 数组
					const combinedItems = res.data.get_question.reduce((acc, entry) => {
						return acc.concat(entry.item);
					}, []);
					combinedItems.forEach(ii => {
						ii.asInfo = {
							choose_as: "",
							choose_as_array: []
						}
					})
					console.log('合并玩的', combinedItems);
					this.totalQuestion = res.data.get_question;
					this.get_questionList = combinedItems;
					const id = combinedItems[0].question_id;
					this.getPaperExamQuestion(id);
				}
			},

			// 试题详情
			async getPaperExamQuestion(id, index = 0) {
				const {
					data: res
				} = await getPaperExamQuestionApi({
					id
				});
				console.log(res, '试题详情');
				this.totalQuestion.forEach(itm => {
					// console.log(itm, 'itm');

				})
				// console.log(res.data, '测试');
				let params = {
					...res.data
				};
				const {
					question_type_name
				} = params;
				params.optionAsList = [{
						key: 'A',
						value: question_type_name === '判断题' ? 'T' : params.option_a,
					},
					{
						key: 'B',
						value: question_type_name === '判断题' ? 'F' : params.option_b,
					},
					{
						key: 'C',
						value: params.option_c,
					},
					{
						key: 'D',
						value: params.option_d,
					},
					{
						key: 'E',
						value: params.option_e,
					},
					{
						key: 'F',
						value: params.option_f,
					},
					{
						key: 'G',
						value: params.option_g,
					}
				]
				params.question = params.question.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');
				if (question_type_name === '填空题' || question_type_name === '提示填空题' || question_type_name === '选词填空题' ||
					question_type_name === '选句填空题') {
					params.question = params.question.replace(/___/g,
						`<input type="text" class="input-box" v-model="answers[${params.choose_as}]"/>`);
				}
				if (question_type_name === '完型填空题' || question_type_name === '选句填空题') {
					console.log(params.get_item);
					params.get_item.forEach(ii => {
						ii.optionAsList = this.createOptionList(ii);
					})
					// params.get_item
				}
				if (question_type_name === '阅读理解题') {
					params.readCurrentTab = 0;
					params.get_item.forEach(ii => {
						ii.optionAsList = this.createOptionList(ii);
					})
				}
				console.log(params.question, 'params');
				this.get_questionList[index].detailInfo = params;
				console.log(this.get_questionList[index], '复制');
			},
			// 定义函数以创建选项列表
			createOptionList(options) {
				const keys = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
				return keys
					.filter((key, index) => options[`option_${key.toLowerCase()}`] !== undefined) // 确保选项存在
					.map(key => ({
						key: key,
						value: options[`option_${key.toLowerCase()}`]
					}));
			},

			// 切换试题
			changeQuestionList(e) {
				const {
					current
				} = e.detail;
				console.log(current, 'current');
				if (current === undefined) return
				const id = this.get_questionList[current].question_id;
				// console.log(current);
				this.current = current;
				console.log(this.get_questionList[current]);
				this.getPaperExamQuestion(id, current)
			},
			// 选择答案
			chooseAs(as, index) {
				console.log(as, 'as');
				console.log(index);
				if (this.get_questionList[index].detailInfo.question_type_name === '多选题') {
					const choose_as_array = this.get_questionList[index].asInfo.choose_as_array;
					// 确保 `choose_as_array` 是数组
					if (!Array.isArray(choose_as_array)) {
						console.error('choose_as_array 不是一个数组');
						return;
					}
					// 推送 `as` 并确保不重复
					if (!choose_as_array.includes(as)) {
						choose_as_array.push(as);
					}
					this.get_questionList[index].asInfo.choose_as_array = [...new Set(choose_as_array)];
					// console.log(this.get_questionList[index].asInfo, 'this.get_questionList[index].asInfo');
				} else {
					this.get_questionList[index].asInfo.choose_as = as;
					// this.addAnswerRecord(this.get_questionList[index])
				}
			},
			// 阅读理解单选
			chooseAsRead(as, index) {

			},
			// 记录答题数据
			async addAnswerRecord(item) {
				console.log(item, 'item');
				console.log(this.examRecordInfo, 'examRecordInfo');
				const correct_status = item.asInfo.choose_as === item.detailInfo.correct_option ? 1 : 0
				const params = {
					paper_exam_record_id: this.examRecordInfo.paper_exam_record_id,
					paper_id: this.examRecordInfo.paper_id,
					paper_exam_id: this.examRecordInfo.paper_exam_id,
					paper_question_id: item.paper_question_id,
					question_id: item.question_id,
					// question_item_id 小题id 阅读理解getItem 的id
					score: correct_status === 1 ? item.score : 0,
					answer: item.asInfo.choose_as,
					// answer_error  选择的单词class （短文改错/单句改错时使用）
					// answer_correct  改正后的单词内容（短文改错/单句改错时使用）
					correct_status
				}
				console.log(params, '记录答题数据请求参数');
				await addAnswerRecordApi(params)
			},
			// 打开答题卡
			openQuestionCard() {
				this.$refs.answerSheet.open();
			},
			// 选择答题卡某一项
			chooseItem(item) {
				// console.log('选择答题卡某一项', item);
				this.current = item.index;
			},
			// 解析答案
			toParse(item) {
				// console.log(item, 'item');
				this.answerList = [item]
				this.$refs.parseAnswerVue.open();
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			onChange(e) {
				// console.log(e, 'e');
				this.timeData = e
			},
			// 阅读理解tab切换
			changeReadTab(pIndex, sIndex) {
				console.log(pIndex, 'pIndex');
				console.log(this.get_questionList[pIndex]);
				this.get_questionList[pIndex].detailInfo.readCurrentTab = sIndex;
			},
			// 交卷
			finishTime() {
				uni.showToast({
					title: '考试时间到,即将前往交卷！',
					icon: 'none'
				});
				setTimeout(() => {
					this.toHandleIn();
				}, 1000);
			},
			handIn() {
				console.log(this.get_questionList);
				let count = 0
				this.get_questionList.forEach(item => {
					console.log(item.asInfo.choose_as);
					if (item.asInfo.choose_as) {
						count += 1
					}
				})
				const unanswered = this.get_questionList.length - count
				console.log(unanswered, 'unanswered');
				let content = unanswered > 0 ? `你还有${unanswered}空未答,点击确定提交试卷，点击取消继续答题!` : '你要提交答案，查看测试结果吗?'
				uni.showModal({
					content,
					success: (res) => {
						if (res.confirm) {
							this.toHandleIn();
						}
					},
				})
			},
			// 去交卷
			toHandleIn() {
				this.examRecordInfo.use_time = this.timeData;
				uni.navigateTo({
					url: '/pages/questionBank/components/handIn/handIn?examRecordInfo=' +
						JSON.stringify(this.examRecordInfo)
				})
				store.commit('paper/set_answerInfo', this.get_questionList);
				store.commit('paper/set_all_answerInfo', this.totalQuestion)
			}
		}
	}
</script>

<style lang="scss" scoped>
	@function px_2_vw($px) {
		@return #{$px * 100 / 1920}vw;
	}

	.page-box {
		background-image: url('../../../../static/images/common/bj-start-test.png');
		background-size: 100% 100%;
		position: relative;
		display: flex;
		flex-direction: column;
		position: relative;
	}

	::v-deep .u-navbar__content__left {
		margin: 0 33rpx !important;
	}

	::v-deep .u-navbar__content__right {
		margin: 0 33rpx !important;
	}

	.u-nav-slot {
		color: #fff;
		font-size: px_2_vw(39);

		.back-box {
			width: px_2_vw(96);
			height: px_2_vw(96);
			border-radius: 50%;
			background-color: #26823E;
		}

		.image1 {
			width: px_2_vw(52);
			height: px_2_vw(63);
		}
	}



	.u-nav-slot-right {
		.answer-sheet {
			width: px_2_vw(225);
			height: px_2_vw(50);
			background: #22A243;
			border-radius: 5rpx;
			padding: 0 13rpx;
			margin-right: 39rpx;

			image {
				width: px_2_vw(34);
				height: px_2_vw(38);
				margin-right: 10rpx;
			}

			span {
				color: #CACACA;
				font-size: px_2_vw(24);
			}
		}

		.hand-in {
			width: px_2_vw(187);
			height: px_2_vw(72);
			font-size: px_2_vw(32);
			border-radius: 27rpx;
			background: #DBDD34;
			color: #B32A2A;
			font-weight: 600;
		}
	}

	.content {
		flex: 1;
		margin-bottom: 33rpx;
		border-radius: 65rpx;
		background: #fff;
		margin: 0 54rpx 33rpx 54rpx;
		position: relative;
		padding: 100rpx 117rpx 51rpx 117rpx;

		.count-down-box {
			position: absolute;
			top: - (px_2_vw(56));
			left: 271rpx;
			background-image: url('../../../../static/images/common/tixing.png');
			background-size: 100% 100%;
			width: px_2_vw(280);
			height: px_2_vw(56);
			color: #fff;
			font-size: px_2_vw(22);
		}

		.time {
			position: absolute;
			bottom: 15rpx;
			left: px_2_vw(45);
		}

		.swiper-box {
			height: 100%;
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			font-weight: 600;
			position: relative;
			// border: 1rpx solid #000;

			.swiper {
				flex: 1;
				// border: 1rpx solid #22A243;
				// margin-bottom: 50rpx;
			}

			.name {
				margin: 42rpx 0;
			}

			.tips {
				color: #707070;
				font-size: px_2_vw(24);
				text-align: center;
			}

			.topic-box {
				.topic-item {
					width: 100%;
					height: px_2_vw(104);
					border-radius: 20rpx;
					background: #D9D5D5;
					margin-bottom: 27rpx;

					font-weight: 600;
					position: relative;
					z-index: 10;

					.options-item {
						padding: 0 59rpx;
					}
				}
			}
		}

		.choose_as {
			border: 1rpx solid #22A243;
		}

		.parase-box {
			position: absolute;
			right: 0;
			bottom: 0;
			color: #b38102;
		}
	}

	.greenColor {
		// background: #0F9F04;
		border: 1rpx solid #0F9F04;
		border-color: #0F9F04 !important;
		color: #0F9F04 !important;
		position: relative;
		z-index: 77;
	}

	.greenColor::after {
		width: 100%;
		height: px_2_vw(104);
		content: '';
		position: absolute;
		top: 0;
		background: RGBA(99, 189, 122, 0.2) !important;
		z-index: 88;
		border-radius: 20rpx;
	}

	.redColor {
		// background: #D11717;
		border: 1rpx solid #D11717;
		border-color: #D11717 !important;
		color: #D11717 !important;
	}

	.redColor::after {
		width: 100%;
		height: px_2_vw(104);
		content: '';
		position: absolute;
		top: 0;
		background: rgba(254, 34, 17, 0.2) !important;
		z-index: 88;
		border-radius: 20rpx;
	}

	.error-icon {
		width: px_2_vw(48);
		height: px_2_vw(48);
		margin-left: 20rpx;
	}

	.name {
		margin: 42rpx 0;

		img {
			width: 100rpx !important;
			height: 100rpx !important;
		}
	}

	.swiper-item-box {
		overflow-y: auto;
		height: calc(100vh - 500rpx);

		// border: 1rpx solid #000;
		.title {
			width: 50%;
		}
	}

	::v-deep .input-box {
		border: none !important;
		outline: none !important;
		border-bottom: 1rpx solid #000 !important;
	}

	.question-box {
		display: flex;
		height: 100%;
		width: 100%;

		.question-box-item {}
	}

	.width50 {
		width: 50% !important;
		height: 90%;
		// border-right: 1rpx dashed #707070;
	}

	.width100 {
		width: 100% !important;
		height: 90%;
	}

	.question-number {
		margin-right: 30rpx;
		color: #707070;
		font-weight: 600;
		margin-bottom: 20rpx;
	}

	.item-write {
		.item-write-sin {
			min-width: px_2_vw(120);
			// height: px_2_vw(48);
			padding: 15rpx 30rpx;
			background: #f4f4f4;
			border-radius: 15rpx;
			margin-right: 10rpx;
			margin-bottom: 20rpx;
		}
	}

	.tab-read-box {
		.tab-read-box-item {
			border-radius: 40rpx;
			padding: 5rpx 30rpx;
			border: 1rpx solid #D9D5D5;
			font-size: px_2_vw(22);
			font-weight: 400;
		}

		.line {
			width: px_2_vw(30);
			border-top: 1rpx solid #D9D5D5;
			height: 1rpx;
			margin: 0 10rpx;
		}
	}

	.current-read {
		border-color: #22A243 !important;
		color: #22A243 !important;
		background: rgba(37, 186, 30, 0.2);
	}

	.read-select-box {
		padding: 40rpx 0;
	}

	// 任务型阅读
	.task-read-input {
		border: 2rpx solid #22A243;
		padding: 20rpx 15rpx;
		border-radius: 15rpx;
		background: rgba(37, 186, 30, 0.2);
		margin-bottom: 20rpx;
	}
</style>